import utils from './utils.js'

let BASE_URL = ''
if (process.env.NODE_ENV === 'development') {
	BASE_URL = 'https://ylx-dev-api.worldintek.com'
} else {
	BASE_URL = 'https://ylx-dev-api.worldintek.com'
}

const _send = function(api, data, options, method, again = 0) {
	return new Promise(async (resolve, reject) => {
		let url = '';
		let config = {
			isNeedLoading: true,
			showLoading: false,
			showErrorMsg: false
		}
		if (options) {
			config = Object.assign({}, config, options)
		}
		let header = {
			'content-type': 'application/json'
		};
		if (config.headers) { // 传递 headers 参数 使用
			header = Object.assign(header, config.headers)
		}
		let isNeedLoading = config.isNeedLoading;
		if (api.indexOf('http') < 0) {
			url = BASE_URL
		}
		url += api;
		console.log('url', url)
		console.log('data==', data)
		let token = uni.getStorageSync('token')
		// console.log('token11', token);
		if (token) {
			header.Authorization = `Bearer ${token}`
		} else {
			if (isNeedLoading) {
				let res = null
				try {
					if (!token) {
						let isRoute = await utils.isGetPageRoutes('pages/login/login')
						!isRoute && uni.reLaunch({
							url: '/pages/login/login'
						})
					} else {
						res = true
					}
				} catch (error) {
					// 在login 重复调用发生冲突时 延迟300ms 后再执行
					await new Promise((resolve, reject) => setTimeout(resolve, 800))
				}

				if (res) {
					header.Authorization = `Bearer ${token}`
				}
			}
		}

		if (config.showLoading) {
			uni.showLoading({
				title: '加载中...',
				mask: true,
			})
		}

		function request() {
			uni.request({
				url,
				data,
				header,
				method,
				success: async (res) => {
					uni.hideLoading()
					if (res.statusCode == 200) {
						if (res.data.code == 401 || res.data.code == 409) {
							try {
								uni.clearStorageSync('token')
								let isRoute = await utils.isGetPageRoutes(
									'pages/login/login')
								if (!isRoute) {
									getApp().globalData.userInfo = null
									uni.reLaunch({
										url: '/pages/login/login'
									})
								}
							} catch (error) {
								// 在login 重复调用发生冲突时 延迟300ms 后再执行
								await new Promise((resolve, reject) => setTimeout(resolve,
									800))
							}
							return resolve(res.data)
						} else if (res.data.code != 200 && config.showErrorMsg) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
						}
						resolve(res.data)
					} else {
						if (config.showErrorMsg) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
						}
						resolve(res.data)
					}
					uni.stopPullDownRefresh()
				},
				fail: (err) => {
					uni.hideLoading()
					uni.showToast({
						title: '当前网络较差',
						icon: 'none'
					})
					resolve({
						code: 0,
						data: {}
					})
				},
				complete: () => {
					uni.hideLoading()
				}
			})
		}
		request(url, data, header, method)
	})
}
const http = {
	post: function(api, data, options) {
		return new Promise((resolve, reject) => {
			_send(api, data, options, 'POST').then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	},
	get: function(api, data, options) {
		return new Promise((resolve, reject) => {
			_send(api, data, options, 'GET').then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	},
	delete: function(api, data, options) {
		return new Promise((resolve, reject) => {
			_send(api, data, options, 'DELETE').then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	},
	put: function(api, data, options) {
		return new Promise((resolve, reject) => {
			_send(api, data, options, 'PUT').then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	},
	BASE_URL: 'https://www.worldintek.com:39011/yaolexue-service/',

}
module.exports = http;